<template>
  <div class="home_article">
    <h2 class="tit">健康资讯新增</h2>
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate">
      <div class="pert">
        <p class="title">基本信息</p>
        <Row class="box">
          <Col span="16">
            <!-- 新闻标题 -->
            <div class="address">
              <div class="left">
                <span class="hongdian">*</span>
                <span>新闻标题：</span>
              </div>
              <FormItem prop="title" class="newstit">
                <Input v-model.trim="formValidate.title" placeholder="输入标题30个汉字以内" :maxlength="30"/>
              </FormItem>
            </div>
          </Col>
          <Col span="8">
            <div class="address">
              <!-- 副酷暑 -->
              <div class="left">
                <span>摘要/副标题：</span>
              </div>
              <FormItem prop="synopsis" class="word">
                <Input v-model.trim="formValidate.synopsis" placeholder="输入标题50个汉字以内" :maxlength="50"/>
              </FormItem>
            </div>
          </Col>
          <Col span="8">
            <!-- <div class="address">
            <div class="left">
              <span>栏目：</span>
            </div>
            <FormItem prop="ids">
              <Select v-model="formValidate.ids" class="lanmu">
                <Option :value="1" :key="1">头条</Option>
                <Option :value="2" :key="2">今日热点</Option>
                <Option :value="3" :key="3">医学前沿</Option>
                <Option :value="4" :key="4">宝宝喂养</Option>
                <Option :value="5" :key="5">科普</Option>
                <Option :value="6" :key="6">决策者说</Option>
              </Select>
            </FormItem>
            </div> -->
            <div class="address">
              <!-- 是否发布： -->
              <div class="left">
                <span>是否发布：</span>
              </div>
              <FormItem>
                <iSwitch v-model="formValidate.enable" size="large">
                  <span slot="open">开启</span>
                  <span slot="close">关闭</span>
                </iSwitch>
              </FormItem>
            </div>
            <!-- 排序： -->
            <div class="address">
              <div class="left">
                <span>优先级：</span>
              </div>
              <FormItem prop="priority">
                <input v-model.trim="formValidate.priority" placeholder="请输入显示序号" class="xuhao inputnumber"
                       @input="srInput"/>
              </FormItem>
            </div>
            <div class="tishi">
              <small>（备注：只能填写数字，1代表置顶以此类推）</small>
            </div>
          </Col>
          <Col span="8">
            <div class="address">
              <!-- 新闻来源： -->
              <div class="left">
                <span>新闻来源：</span>
              </div>
              <FormItem class="laiyuan">
                <Input v-model.trim="formValidate.source" placeholder="输入标题20个汉字以内"/>
              </FormItem>
            </div>
            <Col span="18">
              <div class="address">
                <!-- 小图 -->
                <div class="left">
                  <span>列表首页：</span>
                </div>
                <FormItem>
                  <div class="demo-upload-list" v-for="(item,index) in uploadList" :key='index'>
                    <div v-if="item.status === 'finished'">
                      <img :src="item.url">
                      <div class="demo-upload-list-cover">
                        <Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon>
                        <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                      </div>
                    </div>
                    <div v-else>
                      <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                    </div>
                  </div>
                  <Upload
                    v-show="uploadList.length ==0"
                    ref="upload"
                    :show-upload-list="false"
                    :default-file-list="defaultList"
                    :on-success="handleSuccess"
                    :format="['jpg','jpeg','png']"
                    :max-size="200"
                    :on-format-error="handleFormatError"
                    :before-upload="handleBeforeUpload"
                    :on-exceeded-size="handleMaxSize"
                    multiple
                    type="drag"
                    :action="uploadUrl"
                    :headers="fromData"
                    :data="uploadData"
                    class="picbox"
                  >
                    <div class="pic">
                      <Icon type="ios-camera" size="20"></Icon>
                    </div>
                  </Upload>
                  <Modal title="预览图片" v-model="visible" footer-hide>
                    <img
                      :src="fileBaseUrl + imgName"
                      v-if="visible"
                      style="width: 100%"
                    >
                  </Modal>
                </FormItem>
              </div>
            </Col>
            <Col span="6">
              <RadioGroup v-model="formValidate.pagestyle" size="large">
                <Radio label="1">方图</Radio>
                <Radio label="2">长图</Radio>
              </RadioGroup>
            </Col>
            <Col span="24">
              <div class="ts">
                <small>（备注：图片大小不超过200KB，建议方图170*170px,长图455*200px）</small>
              </div>
            </Col>
          </Col>
          <Col span="8">
            <div class="address">
              <!-- 预设阅读量 -->
              <div class="left">
                <span>预设阅读量：</span>
              </div>
              <FormItem class="readnum">
                <InputNumber style="width:250px" v-model.trim="formValidate.readNum" placeholder="请输入数值" :min="0"
                             :max="99999999999"></InputNumber>
              </FormItem>
            </div>

          </Col>
        </Row>
      </div>
      <div class="pert">
        <p class="title">医生信息</p>
        <Row class="box">
          <Col span="20">
            <div class="address">
              <div class="left">
                <span>选择医生：</span>
              </div>
              <FormItem prop="doctorId" class="newstit">
                <Select
                  class="w-select"
                  @on-change="changeProvince"
                  placeholder="省"
                  v-model="provinceId"
                  :clearable="!provinceStatus"
                  :disabled="provinceStatus"
                >
                  <Option
                    v-for="item in provinceList"
                    :value="item.id"
                    :key="item.id"
                    style='text-align:center;'
                  >{{ item.name }}
                  </Option>
                </Select>
                <Select
                  class="w-select"
                  @on-change="changeCity"
                  placeholder="市"
                  v-model="cityId"
                  :clearable="!cityStatus"
                  :disabled="cityStatus"
                >
                  <Option
                    v-for="(item) in cityList"
                    :value="item.id"
                    :key="item.id"
                    style='text-align:center;'
                  >{{ item.name }}
                  </Option>
                </Select>
                <Select
                  class="w-select"
                  @on-change="changeArea"
                  placeholder="区/县"
                  v-model="areaId"
                  :clearable="!areaStatus"
                  :disabled="areaStatus"
                >
                  <Option
                    v-for="item in areaList"
                    :value="item.id"
                    :key="item.id"
                    style='text-align:center;'
                  >{{ item.name }}
                  </Option>
                </Select>
                <Select
                  class="w-select-hos"
                  placeholder="医院"
                  @on-change="changeDepartment"
                  v-model="hospitalId"
                  :clearable="!hospitalStatus"
                  :disabled="hospitalStatus"
                >
                  <Option
                    v-for="item in hospitalList"
                    :value="item.id"
                    :key="item.id"
                    style='text-align:center;'
                  >{{ item.orgName }}
                  </Option>
                </Select>
                <Select
                  class="w-select"
                  placeholder="科室"
                  @on-change="changeDoctor"
                  v-model="department"
                >
                  <Option
                    v-for="(item,index) in departmentList"
                    :value="item"
                    :key="index"
                    style='text-align:center;'
                  >{{item}}</Option>
                </Select>
                <Select
                  class="w-select"
                  placeholder="医生"
                  v-model="doctorId"
                >
                  <Option
                    v-for="(item,index) in doctorList"
                    :value="item.id"
                    :key="index"
                    style='text-align:center;'
                  >{{item.name}}</Option>
                </Select>
              </FormItem>
            </div>
          </Col>
        </Row>
      </div>
      <div class="pert">
        <p class="title">详细内容</p>
        <Row class="box">
          <Col span="24">
            <!-- 新闻内容 -->
            <FormItem>
              <div>
                <vueEditor
                  id="analysis"
                  :textHtml="editorText"
                  :urlCode="urlCode"
                  @valueHandle="afterChange"
                  :height='100'
                  class="xcon"
                ></vueEditor>
              </div>
            </FormItem>
          </Col>
        </Row>
      </div>
    </Form>
    <div class="queding">
      <Button type="primary" @click="handleSubmit('formValidate')" :disabled='disabledSave' class="btn">
        <Icon type="ios-checkmark icon"/>
        保存
      </Button>
      <Button @click="back" class="btn">
        <i class="iconfont icon-butongyi icon"></i>取消
      </Button>
    </div>
  </div>
</template>

<script>
import vueEditor from "@/components/vueEditor";
import code from "@/configs/base.js";
import api from "@/api/commonApi";
import cookie from "@/utils/cookie.js";

export default {
  components: {
    vueEditor
  },
  data() {
    return {
      id: sessionStorage.getItem("hospitalId"),
      height: 200,
      formValidate: {
        title: "",
        synopsis: "",
        type: "1",
        ids: "",
        priority: "",
        source: "",
        readNum: "",
        pagestyle: "",
        enable: false,
      },
      ruleValidate: {
        title: [{required: true, message: '请输入新闻标题', trigger: 'blur'}],
        synopsis: [{required: true, message: '请输入新闻副标题', trigger: 'blur'}],
        ids: [{required: true, message: '请选择新闻栏目', trigger: 'change', type: "number"}],
        type: [{required: true, message: '请选择新闻类型', trigger: 'change', type: "number"}],
        priority: [{required: true, message: '请输入新闻排序', trigger: 'blur'}],
        source: [{required: true, message: '请输入新闻来源', trigger: 'blur'}],
      },
      // 新闻内容
      editorText: "",
      // 上传图片相关
      imgName: "",
      defaultList: [],
      visible: false,
      uploadList: [],
      uploadModal: true,
      activeUploadId: "5c2bf345-b973-4ffd-a52e-87bb9c1d2b72",
      uploadUrl: api.fileAll,
      uploadData: {json: '{"urlCode":"' + code.urlCode.patientNews + '"}'},
      images: "",
      urlCode: '{"urlCode":"' + code.urlCode.richText + '"}',
      selectList: [
        {
          value: 1,
          label: "头条"
        }
      ],
      disabledSave: false,
      provinceList: [],
      cityList: [],
      areaList: [],
      hospitalList: [],
      departmentList: [],
      doctorList: [],
      cityId: null,
      areaId: null,
      hospitalId: null,
      department: null,
      doctorId: null
    };
  },
  created() {
    let breadList = [
      {path: "/index", title: "首页"},
      {
        path: "/index/publicOperation/healthInformation/list",
        title: "健康资讯管理"
      }
    ];
    this.$emit("changeBreadList", breadList);
    this.provinceList = this.$store.getters.getProvinceList;
    this.cityList = this.$store.getters.getCityList(this.provinceId);
    this.areaList = this.$store.getters.getAreaList(this.cityId);
    console.log(this.provinceList, '==========provinceList')
    console.log(this.cityList, '==========cityList')
    console.log(this.areaList, '==========areaList')
  },
  mounted() {
    this.uploadList = this.$refs.upload.fileList;
  },
  methods: {
    srInput(e) {
      this.formValidate.priority = this.formValidate.priority.replace(/[^0-9]/g, '')
      if (e.target.value > 9999) this.formValidate.priority = 9999
    },
    afterChange(val) {
      this.editorText = val;
    },
    handleView(name) {
      this.imgName = name;
      this.visible = true;
    },
    handleRemove(file) {
      const fileList = this.$refs.upload.fileList;
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
    },
    handleSuccess(res, file) {
      res = this.uploadFileDecrypt(res);
      file.url = this.fileBaseUrl + res.object[0].fileName;
      this.images = JSON.stringify(res.object[0]);
      file.name = res.object[0].fileName;
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: "格式错误",
        desc: "文件 " + file.name + " 上传失败,请重试"
      });
    },
    handleBeforeUpload(file) {
      const check = this.uploadList.length < 1;
      if (!check) {
        this.$Message.info("只能上传一张图片");
      }
      return check;
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "文件过大",
        desc: `文件${file.name}过大，文件最大限制为200KB`
      });
    },
    back() {
      let query = this.$route.query;
      this.functionJS.queryNavgationTo(
        this,
        "/index/publicOperation/healthInformation/list",
        query
        //公用方法
      );
    },
    //保存
    handleSubmit(name) {
      this.disabledSave = true
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (!this.editorText) {
            this.$Message.error("请输入新闻内容");
            this.disabledSave = false
          } else {
            //把页面上的参数获取到
            let params = {
              ids: [this.formValidate.ids],
              //内容
              content: this.editorText.replaceAll("<p>&nbsp;</p>", ""),
              dhtboOperateArticle: {
                title: this.formValidate.title.trim(),
                abStract: this.formValidate.synopsis.trim(),
                showIndex: this.formValidate.priority,
                source: this.formValidate.source,
                readNum: this.formValidate.readNum,
                pageStyle: Number(this.formValidate.pagestyle),
                isEnable: Number(this.formValidate.enable),
                type: this.formValidate.type,
                doctorId: this.doctorId
              }
            };
            let images = "";
            if (this.images && this.uploadList.length) {
              images = this.images;
            } else if (this.uploadList.length) {
              images = this.uploadList[0].url;
            } else {
              images = "";
            }
            params.dhtboOperateArticle.coverImg = images;
            this.$axios
              .post(api.insertArticle, params)
              .then(res => {
                if (res.data.code) {
                  this.$Message.info("添加成功");
                  let query = this.$route.query
                  let pageNo = this.$route.query.pageNo ? Number(this.$route.query.pageNo) : 1
                  let type2 = this.$route.query.type2 ? Number(this.$route.query.type2) : null
                  // setTimeout(() => {
                  this.disabledSave = false
                  this.back();
                  // }, 5000);
                } else {
                  this.disabledSave = false
                  this.$Message.info("添加失败请重试");
                }
              })
              .catch(err => {
                this.disabledSave = false
                console.log(err);
              });
          }
        } else {
          this.$Message.error('请完整填写必填项!');
          this.disabledSave = false
        }
      })
    },
    changeProvince() {
      this.cityId = null;
      this.areaId = null;
      this.hospitalId = null;
      this.cityList = this.$store.getters.getCityList(this.provinceId);
      this.hospitalList = null;
    },
    changeCity() {
      this.areaId = null;
      this.hospitalId = null;
      this.areaList = this.$store.getters.getAreaList(this.cityId);
      this.hospitalList = null;
    },
    changeArea() {
      this.hospitalId = null;
      this.hospitalList = null;
      var params = {};
      params.provinceCode = parseInt(
        this.provinceId == 0 ? null : this.provinceId
      );
      params.cityCode = parseInt(
        this.cityId == 0 ? null : this.cityId
      );
      params.districtCode = parseInt(
        this.areaId == 0 ? null : this.areaId
      );
      console.log('参数',params)
      this.$axios
        .post(api.findHospitalListByProvinceCode, params)
        .then(resp => {
          this.hospitalList = resp.data.object;
          console.log(this.hospitalList)
        })
        .catch(err => {
          console.log(err);
        });
    },
    changeDepartment(){
      console.log(this.hospitalId)
      var params = {};
      params.hospitalId = parseInt(
        this.hospitalId == 0 ? null : this.hospitalId
      );
      this.$axios
        .post(api.departmentList, params)
        .then(resp => {
          this.departmentList = resp.data.object;
        })
        .catch(err => {
          console.log(err);
        });
    },
    changeDoctor(){
      var params = {};
      params.department = this.department;
      params.hospitalId = this.hospitalId;
      this.$axios
        .post(api.findDepartmentsAllDoctor, params,{
          headers: {
            'Content-Type': 'application/json'
          }
        })
        .then(resp => {
          this.doctorList = resp.data.object;
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
};
</script>

<style scoped lang="less">
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}

.demo-upload-list img {
  width: 100%;
  height: 100%;
}

.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}

.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}

.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}

.home_article {
  width: calc(100%);
  padding: 10px 0px;
  margin: 0 auto;
  background: #fff;

  .tit {
    margin: 10px 0;
    font-weight: bold;
    text-align: center;
  }

  Input {
    display: inline-block;
    width: 100%;
    border: 1px solid black;
    line-height: 30px;
    outline: none;
    text-indent: 5px;
  }

  .pert {
    width: 98%;
    display: flex;
    flex-direction: column;
    margin: 10px auto;
    border: 1px solid #f0f0f0;
    box-shadow: 0 4px 3px #ebedf8;
    border-radius: 5px;
    margin-bottom: 20px;

    .title {
      font-size: 20px;
      padding-left: 15px;
      margin-bottom: 20px;
      color: #333;
      height: 40px;
      line-height: 40px;
      background: #ebedf8;
    }

    .address {

      display: flex;
      flex-direction: row;

      .left {
        font-size: 14px;
        padding-top: 5px;

        span:last-child {
          margin-right: 5px;
        }

        .hongdian {
          color: red;
          margin-left: -10px;
        }
      }
    }

    .box {
      padding: 0 50px;
    }

    .newstit {
      width: 86%;
    }

    .word {
      width: 75%;
    }

    .lanmu {
      width: 120px;
    }

    .xuhao {
      width: 120px;
    }

    .tishi {
      margin: 0px 0 20px 0;
      color: #ff9966;
    }

    .ts {
      margin: -20px 0 20px 0;
      color: #ff9966;
    }

    .laiyuan {
      width: 72%;
    }

    .readnum {
      width: 76%;
    }

    .picbox {
      display: inline-block;
      width: 58px;
    }

    .pic {
      width: 58px;
      height: 58px;
      line-height: 58px;
    }

    .xcon {
      margin: 0;
      width: 100%;
    }

    .inputnumber {
      width: 100%;
      background: #fff;
      border: none;
      outline: none;
      text-indent: 10px;
      line-height: 30px;
      border: 1px solid #ddd;
      border-radius: 4px;
      color: #666;
    }

    .inputnumber:focus {
      border-color: #5362e1
    }
  }

  /*保存*/

  .queding {
    width: 100%;
    text-align: center;

    .btn {
      width: 75px;
      height: 35px;
    }
  }

  .icon {
    font-size: 14px;
    margin-right: 5px;
  }
}

.w-select {
  width: 105px;
}

.w-select-hos {
  width: 180px;
}

</style>
